import traceback

from PyQt5.QtCore import QDate
from PyQt5.QtWidgets import QMessageBox, QHeaderView

from dao.rapid_country_db import RapidCountryManager
from enums.bank_enum import BankEnum

from base.base import BaseGui
from dao.rapid_bank_db import RapidBankManager
from rapid_api.crawler_bank_for_country import get_bank_total
from utils.button_tablewidget import WithButtonTableWidget
from utils.excel import ExportExcelDialog


class BankGui(BaseGui):

    def __init__(self):
        super().__init__()

        self.bank_page_size = 10  # 默认分页数
        self.bank_page_num = 1  # 默认分页
        self.bank_headers = BankEnum.getDescList()
        self.bankTableWidget = self.ui.bankTableWidget
        self.bank_page_data = None  # 当前页数据

        try:
            # 根据国家查询
            self.ui.countryByBankPushButton.clicked.connect(self.indexBankByCountry)
            # 根据银行查询
            self.ui.bankPushButton.clicked.connect(self.indexByBank)
            # 分页展示第一页
            self.bank_show_page(page_num=self.bank_page_num)
            # 下一页
            self.ui.bank_page_down.clicked.connect(self.bank_page_down)
            # 上一页
            self.ui.bank_page_up.clicked.connect(self.bank_page_up)
            # 导出 bank列表
            # self.ui.exportBankPushButton.clicked.connect(self.exportBanks)
            # 一键获取所有银行的数据
            # self.ui.pushButton.clicked.connect(self.oneClickRetrieval)

        except Exception as e:
            traceback.print_exc()
            QMessageBox.about(self.ui, "账号页点击错误", str(e))

    def bank_show_page(self, page_num):
        self.bankTableWidget.clear()
        self.bank_page_data = None
        query_columns = BankEnum.getValuesStr()
        start = (page_num - 1) * self.bank_page_size
        rapidBankManager = RapidBankManager()
        self.bank_page_data = rapidBankManager.selectDataByPager(start, pageSize=self.bank_page_size,
                                                                 query_columns=query_columns)
        WithButtonTableWidget(self, self.bankTableWidget, self.bank_page_data, self.bank_headers, 4)
        self.bankTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

    def bank_page_down(self):
        self.bank_page_num += 1
        self.bank_show_page(self.bank_page_num)

    def bank_page_up(self):
        self.bank_page_num -= 1
        if self.bank_page_num == 0:
            self.bank_page_num = 1
        self.bank_show_page(self.bank_page_num)

    def indexBankByCountry(self):
        text = self.ui.bankLineEdit.text()
        if len(text) == 0:
            self.bank_show_page(1)
            return
        country = RapidCountryManager()
        country_info = country.selectInfoByCountry(text, "country, country_abbr")
        if country_info is not None and len(country_info) > 0:
            rapidBankManager = RapidBankManager()
            query_columns = BankEnum.getValuesStr()
            bank_list = rapidBankManager.selectListByCountry(country_info[0][1], query_columns)
            if len(bank_list) > 0:
                self.bankTableWidget.clear()
                WithButtonTableWidget(self, self.bankTableWidget, bank_list, self.bank_headers, 4)
            else:
                result = get_bank_total(country_info[0][1])
                if result is not None:
                    rapidBankManager1 = RapidBankManager()
                    print(f"获取返回银行信息：{result}")
                    rapidBankManager1.batchInsertBankByTuple(result, tuple(BankEnum.getValuesList()))
                else:
                    QMessageBox.about(self.ui, "error", f'当前Bank 查无数据')
                    return
        else:
            QMessageBox.about(self.ui, "error", f'当前国家信息暂无，无法去获得银行信息')
            return
        self.bankTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)


    def indexByBank(self):
        text = self.ui.bankLineEdit.text()
        if len(text) == 0:
            self.bank_show_page(1)
            return
        rapidBankManager = RapidBankManager()
        query_columns = BankEnum.getValuesStr()
        rapidBank = rapidBankManager.selectInfoByBank(text, query_columns)
        if rapidBank is not None and len(rapidBank) > 0:
            self.bankTableWidget.clear()
            WithButtonTableWidget(self, self.bankTableWidget, rapidBank, self.bank_headers, 4)
        else:
            QMessageBox.about(self.ui, "error", f'当前Bank 查无数据')
            return
        self.bankTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

    def exportBanks(self):
        rapid = RapidBankManager()
        start_time = QDate.currentDate().addDays(-3).toString("yyyy-MM-dd")  # 可拓展为页面选择
        end_time = QDate.currentDate().addDays(1).toString("yyyy-MM-dd")
        data = rapid.selectExportData(start_time, end_time)
        ExportExcelDialog(data)
        QMessageBox.about(self.ui, "导出银行信息", f'导出数据：{len(data)} 条')

    def oneClickRetrieval(self):
        rapid = RapidCountryManager()
        data = rapid.selectDataByPager(0, 1000, "country, country_abbr")
        if data is not None and len(data) > 0:
            for item in data:
                rapidBankManager = RapidBankManager()
                banks = rapidBankManager.selectListByCountry(item[1])
                if len(banks) > 0:
                    print(f"{item[1]} 已存在 ：{len(banks)} 条")
                    continue
                result = get_bank_total(item[1])
                if result is not None and len(result) > 0:
                    rapidBankManager1 = RapidBankManager()
                    print(f"获取返回银行信息1：{result}")
                    rapidBankManager1.batchInsertBankByTuple(result, tuple(BankEnum.getValuesList()))
                else:
                    print(f"当前国家 查无银行数据：{item[1]}")
                    continue
